package thread;

public class Demo12 {

    private static long count = 0;
    public static void main(String[] args) throws InterruptedException {
        Object object = new Object();
        Thread t1 = new Thread(()->{
            for (int i = 0; i < 5000; i++) {
                //两个线程分别对count++过程加锁
                synchronized (object){
                    count++;
                }
            }
        });

        Thread t2 = new Thread(()-> {
            for (int i = 0; i < 5000; i++) {
                //两个线程分别对count++过程加锁
                synchronized (object) {
                    count++;
                }
            }
            //如果这样加锁会失去并发执行效果，t1线程循环执行结束后t2线程循环才开始执行
            /*synchronized (object) {
                for (int i = 0; i < 5000; i++) {
                    count++;
                }
            }*/
        });

        t1.start();
        t2.start();

        ///main阻塞等待t1和t2
        t1.join();
        t2.join();
        System.out.println(count);
    }
}
